﻿using B.S.BasicData.Api.Write.DTOs;
using B.S.BasicData.ErrorCode;
using Consul;

namespace B.S.BasicData.Api.Write.InnerApi
{

    /// <summary>
    /// 自定义的服务发现
    /// </summary>
    public class ServiceDiscovery
    {
        private readonly IConsulClient consulClient;
        private readonly HttpClient httpClient;

        public ServiceDiscovery(IConsulClient consulClient, IHttpClientFactory httpClient)
        {
            this.consulClient = consulClient;
            this.httpClient = httpClient.CreateClient();
        }
        //ApiPaging<AccountListDTO> //需要http
        /// <summary>
        /// 封装一个找ip+端口+api,得到url的方法
        /// </summary>
        /// <param name="serviceName">服务名字</param>
        /// <param name="apiName">要调用的api的接口</param>
        /// <returns></returns>
        public async Task<string> GetUrl(string serviceName,string apiName) {

            //取实例的ip+port
            var services = await consulClient.Health.Service(serviceName);  //实例列表

            var allCount = services.Response.Length; //所有实例的个数
            var index = new Random().Next(0, allCount - 1);//随机取一个实例
            var service = services.Response[index]; //取出了一个实例
            var ip = service.Service.Address; //ip地址
            var port  = service.Service.Port; //端口
            //http://localhost:5141/api/Account/GetSalt
            string url = $"http://{ip}:{port}{apiName}";            
            return url;
        }

        public async Task<ApiPaging<AccountListDTO>>  GetAccount(string url) {

            var uri = new Uri(url);
            var res = await  httpClient.GetAsync(uri);
            res.EnsureSuccessStatusCode();
            return await res.Content.ReadFromJsonAsync<ApiPaging<AccountListDTO>>();
            
        }
    }
}
